package com.saifan.wyy_ov.ui.user;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.data.bean.RegistorBean;
import com.saifan.wyy_ov.config.Api;
import com.saifan.wyy_ov.model.impl.GetData;
import com.saifan.wyy_ov.model.interfaces.IGetData;
import com.saifan.wyy_ov.model.interfaces.ResponseData;
import com.saifan.wyy_ov.ui.view.BootstrapButton;
import com.saifan.wyy_ov.utils.DialogUtil;
import com.saifan.wyy_ov.utils.StringUtil;
import com.saifan.wyy_ov.utils.ToastUtil;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

import static com.mob.tools.utils.R.getStringRes;


public class RegisterActivity extends AppCompatActivity {

    private android.support.v7.widget.Toolbar toolbar;
    private android.widget.EditText phone;
    private android.widget.Button getcode;
    private android.widget.EditText code;
    private android.widget.EditText password;
    private android.widget.EditText repassword;
    private com.saifan.wyy_ov.ui.view.BootstrapButton submit;
    // 填写从短信SDK应用后台注册得到的APPKEY
    private static String APPKEY;//
    // 填写从短信SDK应用后台注册得到的APPSECRET
    private static String APPSECRET;//
    private TimeCount mTimeCount;
    private RegistorBean mRegistorBean;
    private IGetData mGetData;
    private boolean smsFlag = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        APPKEY = getResources().getString(R.string.sms_appkey);
        APPSECRET = getResources().getString(R.string.sms_appsecret);
        setupViews();
    }

    private void setupViews() {
        this.toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        this.submit = (BootstrapButton) findViewById(R.id.submit);
        this.repassword = (EditText) findViewById(R.id.repassword);
        this.password = (EditText) findViewById(R.id.password);
        this.code = (EditText) findViewById(R.id.code);
        this.getcode = (Button) findViewById(R.id.get_code);
        this.phone = (EditText) findViewById(R.id.phone);
        mTimeCount = new TimeCount(90000, 1000);
        SMSSDK.initSDK(this, APPKEY, APPSECRET, false);
        EventHandler eh = new EventHandler() {

            @Override
            public void afterEvent(int event, int result, Object data) {

                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                handler.sendMessage(msg);
            }

        };
        SMSSDK.registerEventHandler(eh);

        getcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(phone.getText().toString())) {
                    if (!StringUtil.checkPhoneNum(phone.getText().toString())) {
                        ToastUtil.showToast(RegisterActivity.this, "请输入正确的手机号");
                        return;
                    }
                    SMSSDK.getVerificationCode("86", phone.getText().toString());
                    mTimeCount.start();
                } else {
                    ToastUtil.showToast(RegisterActivity.this, "电话号码不能为空");
                }
            }
        });
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(code.getText().toString())) {
                    if (TextUtils.isEmpty(password.getText().toString())) {
                        ToastUtil.showToast(RegisterActivity.this, "请输入密码");
                        return;
                    }
                    if (TextUtils.isEmpty(repassword.getText().toString())) {
                        ToastUtil.showToast(RegisterActivity.this, "请确认密码");
                        return;
                    }
                    DialogUtil.showProgressDialog(RegisterActivity.this, "正在请求...");
                    if (smsFlag) {
                        registor();
                        return;
                    }
                    SMSSDK.submitVerificationCode("86", phone.getText().toString(), code.getText().toString());
                } else {
                    ToastUtil.showToast(RegisterActivity.this, "验证码不能为空");
                }
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            this.finish();
        }
        return super.onOptionsItemSelected(item);
    }

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            int event = msg.arg1;
            int result = msg.arg2;
            Object data = msg.obj;
            Log.e("event", "event=" + event);
            if (result == SMSSDK.RESULT_COMPLETE) {
                //短信注册成功后，返回MainActivity,然后提示新好友
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {//提交验证码成功
                    smsFlag = true;
                    phone.setEnabled(false);
                    getcode.setEnabled(false);
                    code.setEnabled(false);
                    registor();
                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    Toast.makeText(getApplicationContext(), "验证码已经发送", Toast.LENGTH_SHORT).show();
                } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {//返回支持发送验证码的国家列表
                    Toast.makeText(getApplicationContext(), "获取国家列表成功", Toast.LENGTH_SHORT).show();
                }
            } else {
                ((Throwable) data).printStackTrace();
                int resId = getStringRes(RegisterActivity.this, "smssdk_network_error");
                DialogUtil.closeProgressDialog();
                Toast.makeText(RegisterActivity.this, "验证码错误", Toast.LENGTH_SHORT).show();
                if (resId > 0) {
                    Toast.makeText(RegisterActivity.this, resId, Toast.LENGTH_SHORT).show();
                }
            }

        }

    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterAllEventHandler();
    }

    class TimeCount extends CountDownTimer {

        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);//参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onTick(long millisUntilFinished) {//计时完毕时触发
            getcode.setClickable(false);
            getcode.setText(millisUntilFinished / 1000 + " 秒");
        }

        @Override
        public void onFinish() {
            getcode.setClickable(true);
            getcode.setText("重新发送");
        }
    }

    private void registor() {
        if (mGetData == null) {
            mGetData = new GetData();
        }
        if (mRegistorBean == null)
            mRegistorBean = new RegistorBean();
        mRegistorBean.setYK_YHM(phone.getText().toString());
        mRegistorBean.setYK_MM(password.getText().toString());
        mGetData.getDataJson(RegisterActivity.this, Api.Customer.REGISTER, mRegistorBean,
                null, new ResponseData() {
                    @Override
                    public void onSuccess(String json) {
                        ToastUtil.showToast(RegisterActivity.this, "注册成功");
                        RegisterActivity.this.finish();
                    }

                    @Override
                    public void onFailed(String str) {

                    }
                });
    }

}
